package com.suxin.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Classname TestMain_1
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/10/26 20:58
 * @Created by ASUS
 */
public class MedisClient {

    private String host;

    private Integer port;

    private String password;

    private static final String DEFAULT_HOST = "127.0.0.1";

    private static final int DEFAULT_PORT = 6379;

    private static final int DEFAULT_TIMEOUT = 2000;

    private InputStream inputStream;
    private OutputStream outputStream;

    public MedisClient() {
        this(DEFAULT_HOST, DEFAULT_PORT);
    }

    public MedisClient(String host,Integer port) {
        this(host, port, null);
    }

    public MedisClient(String host, Integer port, String password) {
        this.host = host;
        this.port = port;
        this.password = password;

        try {
            createSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Socket createSocket() throws Exception {
        Socket socket = new Socket("127.0.0.1",6379);
        socket.setKeepAlive(true);
        socket.setReuseAddress(true);
        socket.setTcpNoDelay(true);
        socket.setSoLinger(true, 0);
//        socket.connect(new InetSocketAddress(host, port), DEFAULT_TIMEOUT);
        socket.setSoTimeout(DEFAULT_TIMEOUT);
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        return socket;
    }

    public String command(String cmd) throws Exception {
        outputStream.write((cmd + "\r\n").getBytes());
        outputStream.flush();
        // 等待输入流有内容
        while (inputStream.available() == 0) {
        }
        byte[] bt = new byte[inputStream.available()];
        inputStream.read(bt);
        String result = new String(bt);
        System.out.println(String.format("服务器返回的结果为：%s", result.replace("\r\n", "\\r\\n")));
        return result;
    }

    public static void main(String[] args) throws Exception{
        MedisClient medisClient = new MedisClient("127.0.0.1", 6379);
        while (true) {
            Scanner scanner = new Scanner(System.in);
            if (scanner.hasNextLine()) {
                String cmd = scanner.nextLine();
                medisClient.command(cmd);
            }
        }
    }
}